package com.lanyou.esb.redis.proxy.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.common.CommonUtils;
import com.lanyou.esb.common.Constants4Redis;
import com.lanyou.esb.redis.JedisPoolUtils;
import com.lanyou.esb.redis.proxy.base.BaseHashJedisProxy;
import com.lanyou.esb.redis.vo.IfTokenVo;

/**
 * 接口令牌Redis操作代理
 * 
 * @author Davey.wu
 */
@Service
public class TokenJedisProxy extends BaseHashJedisProxy<IfTokenVo> {

	/****/
	private static final String HASH_KEY_FOR_TEST_TOKEN = Constants4Redis.REDIS_HASH_KEY_TOKEN_TEST;

	public TokenJedisProxy() {
		this.setHashKey(Constants4Redis.REDIS_HASH_KEY_TOKEN);

		/** field的组成：系统编码，接口编码，接口版本，调用方系统编码 **/
		Map<String, Integer> keyFields = new HashMap<>();
		keyFields.put(CommonUtils.SYSTEM_CODE, 0);
		keyFields.put(CommonUtils.INTERFACE_CODE, 1);
		keyFields.put(CommonUtils.INTERFACE_VERSION, 2);
		keyFields.put(CommonUtils.CALL_SYSTEM_CODE, 3);
		this.setKeyFields(keyFields);
	}

	@Override
	public long hset(String key, IfTokenVo target)
			throws JsonProcessingException {
		Long result = 0l;
		String json = this.toJson(target);
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			// 服务请求会用到
			result = jedis.hset(this.getHashKey(), key, json);
			// 申请访问令牌会用到
			result = jedis
					.hset(this.getHashKey(), this.getAppKey(target), json);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (result == null) {
			return 0l;
		}
		return result;
	}

	@Override
	public Map<String, String> getKeyMap(IfTokenVo token) {
		Map<String, String> map = new HashMap<>(4);
		map.put(CommonUtils.SYSTEM_CODE, token.getPubSystemCode());
		map.put(CommonUtils.INTERFACE_CODE, token.getIfCode());
		map.put(CommonUtils.INTERFACE_VERSION, token.getIfVersion());
		map.put(CommonUtils.CALL_SYSTEM_CODE, token.getCallSytemCode());
		return map;
	}

	/**
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 * 
	 */
	public IfTokenVo getHash4TestToken(String key) throws JsonParseException,
			JsonMappingException, IOException {
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return null;
		}
		boolean broken = false;
		try {
			result = jedis.hget(HASH_KEY_FOR_TEST_TOKEN, key);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}

		if (StringUtils.isBlank(result)) {
			return null;
		}
		return fromJson(result);
	}

	/**
	 * 保存测试访问令牌
	 * 
	 * @param key
	 * @param target
	 * @return
	 * @throws JsonProcessingException
	 */
	public long saveHash4TestToken(String key, IfTokenVo target)
			throws JsonProcessingException {
		Long result = 0l;
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			result = jedis.hset(HASH_KEY_FOR_TEST_TOKEN, key,
					this.toJson(target));
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (result == null) {
			return 0l;
		}
		return result;
	}

	/**
	 * 根据密钥查找令牌的键值
	 * 
	 * @param token
	 * @return
	 */
	private String getAppKey(IfTokenVo token) {
		return token.getAppKey() + KEY_SEPARATOR + token.getPubSystemCode()
				+ KEY_SEPARATOR + token.getIfCode() + KEY_SEPARATOR
				+ token.getIfVersion();
	}
}
